<?php

$s = !empty($_GPC['s']) ? $_GPC[s] : 'plan';


$frames = buildframes(array('base', 'plan', 'grant', 'finance'));

$frames = $frames[$system];


define('AUDIT', 1);
define('PASS', 2);
define('NOPASS', 3);
define('DELETED', 4);

$user = $_W['user'];

function getBizStatus()
{
    //未审核，通过，不通过，已删除
    static $status = array(0 => '创建', 1 => '请求审核', 2 => '通过', 3 => '不通过', 4 => '已删除');
    return $status;
}

function getGeneStatus()
{
    static $status = array(0 => '停用', 1 => '启用');
    return $status;
}

function getDictData($parent = 0, $useKey = false)
{
    $sql = "SELECT * FROM " . tablename($table) . "  WHERE parent ={$parent}  ";
    if ($useKey) {
        return pdo_fetchall($sql, array(), 'id');
    } else {
        return pdo_fetchall($sql);
    }
}

function getTemplate($id)
{
    $sql = 'select * from ' . tablename('sms_template') . ' where id=:id';
    return pdo_fetch($sql, array(':id' => $id));

}


function getItemshtml($data, $field = 'title')
{
    $items = json_decode($data, true);
    $d = array();
    foreach ($items as $k => $v) {
        $d[] = $v[$field];
    }
    return implode('、', $d);
}

function getGroupTitle($id)
{
    return pdo_fetchcolumn("SELECT title FROM " . tablename('send_group') . " where id=:id", array(':id' => $id));
}

function getSendeeByGroup($id)
{

    $sql = "SELECT * FROM " . tablename('send_group') . " where id=:id";
    $row = pdo_fetch($sql, array(':id' => $id));
    if ($row) {
        return json_decode($row['sendee'], true);
    } else {
        return false;
    }
}

function getSendeeByIds($ids)
{
    if (is_array($ids)) {
        $ids = implode(',', $ids);
    }
    $sql = "SELECT * FROM " . tablename('sms_sendee') . " where id in ($ids)";
    return pdo_fetchall($sql, array(), 'id'); //. " WHERE status = 0"
}

function getMsgByIds($ids)
{
    if (is_array($ids)) {
        $ids = implode(',', $ids);
    }
    $sql = "SELECT * FROM " . tablename('dictionary') . " WHERE id in ($ids)";
    return pdo_fetchall($sql, array(), 'id');
}

function getAllSendee($useId = false)
{
    return pdo_fetchall("SELECT * FROM " . tablename('sms_sendee'), array(), $useId ? 'id' : ''); //. " WHERE status = 0"
}

function getSendGroup()
{
    return pdo_fetchall('select * from ' . tablename('send_group'), array(), 'id');
}

function getTemplates($type = 0)
{
    $sql = 'select * from ' . tablename('sms_template');
    if ($type > 0) {
        $sql .= ' where type=' . $type;
    }
    return pdo_fetchall($sql, array(), 'id');
}

function getDevices()
{
    static $devices = array(0 => '手机', 1 => 'LED');
    return $devices;
}

//region 权限处理

function getOperate()
{
    static $op = array(
        'disp' => array(
            'id' => 1,
            'name' => 'disp',
            'title' => '查看',
            'icon' => 'search'
        ),
        'add' => array(
            'id' => 2,
            'name' => 'add',
            'title' => '增加',
            'icon' => 'add'
        ),
        'edit' => array(
            'id' => 4,
            'name' => 'edit',
            'title' => '修改',
            'icon' => 'edit'
        ),
        'delete' => array(
            'id' => 8,
            'name' => 'delete',
            'title' => '删除',
            'icon' => 'remove'
        ),
        'audit' => array(
            'id' => 16,
            'name' => 'audit',
            'title' => '审核',
            'icon' => 'audi'
        ),
    );
    return $op;
}

function getModules()
{
    static $modules = array(
        'plan' => array(
            'name' => 'plan',
            'title' => '监测通知',
            'id' => 1,
        ),
        'grant' => array(
            'name' => 'grant',
            'title' => '拨款凭证信息',
            'id' => 2,

        ),
        'finance' => array(
            'name' => 'finance',
            'title' => '库款划拨信息',
            'id' => 3,
        ),

    );
    return $modules;
}

function getModuleDict()
{
    $m = array();
    $list = getModules();
    foreach ($list as $k => $v) {
        $m[$v['id']] = $v['title'];
    }
    return $m;
}

function getModuleId($name)
{
    $id = 0;
    $m = getModules();
    if (!empty($m[$name])) {
        $id = $m[$name]['id'];
    }
    return $id;
}

function checkRecodeRight($recode, $user, $op, $tip = true)
{
    $operates = getRecodeOperates($recode, $user);
    $enable = in_array($op, $operates);
    if (!$enable && $tip) {
        message('数据禁止访问！');
    }
    return $enable;
}

function checkModuleRight($user, $module, $op, $tip = true)
{
    if($user['isfounder']){
        return true;
    }
    //检查用户操作权限permission
    $operate=$module.'/'.$op;

    $enable = in_array($operate, $user['right']);
    if (!$enable && $tip) {
        message('数据禁止访问！');
    }
    return $enable;
}

function geneCtrlBtn($recode, $user, $module)
{
    $operates = getOperate();
    $op = getRecodeOperates($recode, $user);
    $html = '';
    if($module=='finance' && $recode['status']==PASS&&checkModuleRight($user, 'finance', 'add',false)){
        $url = url("finance/finance/add", array('id' => $recode['id']));
        $html .= "<a href='{$url}'>新增拔款</a>&nbsp;";
    }
    foreach ($op as $o) {
        if(checkModuleRight($user, $module, $o,false)){
            $url = url("{$module}/{$module}/{$o}", array('id' => $recode['id']));
            $title = $operates[$o]['title'];
            $js = '';
            if ($o == 'delete') {
                $js = ' onclick="return confirm(\'确认删除吗？\');return false;" ';
            }
            $html .= "<a href='{$url}' {$js}>{$title}</a>&nbsp;";
        }
    }

    return $html;
}


function getUserOperate($user, $module)
{
    $mid=getModuleId($module);
    //所有模块功能转换为二进制列表分组
    //从用户模
    $operates = getOperate();

    return array_keys($operates);
}


function getRecodeOperates($recode, $user)
{
    $op = array();
    if (isset($recode['status'])) {
        $status = $recode['status'];
        $op[] = 'disp';
        if ($recode['createid'] == $user['uid']) {
            if ($status != DELETED) {
                if (($status == 0) || ($status == NOPASS)) {

                    $op[] = 'edit';
                    $op[] = 'delete';

                }
            }
        } else {
            //用户是否有当前模块的审核权限
            if ($status == AUDIT) {
                $op[] = 'audit';
            }
        }
    }
    return $op;
}

//endregion

function getTemplateFields($id)
{
    $fields = array();
    switch ($id) {
        case 1:
            $fields[] = array(
                'tag' => '[时间]',
                'field' => 'date',
            );
            $fields[] = array(
                'tag' => '[付款单位]',
                'field' => 'payer',
            );
            $fields[] = array(
                'tag' => '[收款单位]',
                'field' => 'payee',
            );
            $fields[] = array(
                'tag' => '[金额]',
                'field' => 'money',
            );
            $fields[] = array(
                'tag' => '[目的]',
                'field' => 'purpose',
            );
            break;
    }
    return $fields;
}

function procGrantContent($data)
{
    //[时间]
    global $_W;
    $temp = $_W['config']['GRANT_Temp'];
    if (empty($temp)) {
        $temp = '[付款单位]向[收款单位]支付[金额]元，用于"[目的]"。';
    }
    $field = getTemplateFields(1);
    $tags = array();
    $values = array();
    foreach ($field as $f) {
        if (isset($data[$f['field']])) {
            $tags[] = $f['tag'];
            $values[] = $data[$f['field']];
        }
    }
    return str_replace($tags, $values, $temp);
}

function addSMSOutBox($db, $send)
{
    $sql = "INSERT INTO Outbox (ExpressLevel,ReceiverMobileNo,Msg) VALUES (0,?,?)";
    $add = 0;
    //$db = new MSSQL_DB($_W['config']['sms'], 'mssql');
    try {
        $params = array($send['mobile'], $send['content']);

        if ($db->query($sql, $params)) {
            $add = 1;
        }
    } catch (Exception $e) {
        $add = 0;
    }
    return $add;
}

function getSMSMsg($pid, $module)
{
    //获取发送短信信息列表，$pid发送记录时的id，$module对应模块
    $mid = getModuleId($module);
    if (is_array($pid)) {
        $pid = $pid['id'];
    }
    $sql = 'select * from ' . tablename('out_box') . ' where parentid=:pid and moduleid=:mid';
    return pdo_fetchall($sql, array(':pid' => $pid, ':mid' => $mid));
}

function addSMSMsg($data, $module)
{
    if (empty($data['sendee'])) {
        return false;
    }
    load()->classs('mssql');
    global $_W;
    $db = new MSSQL_DB($_W['config']['sms'], 'mssql');
    $mid = getModuleId($module);
    $selects = empty($data['sendee']) ? array() : json_decode($data['sendee'], true);
    foreach ($selects as $s) {
        $msg = array(
            'parentid' => $data['id'],
            'content' => $data['content'],
            'moduleid' => $mid,
            'seedeeid' => $s['id'],
            'mobile' => $s['mobile'],
            'device' => $s['device'],
            'sendtime' => TIMESTAMP,
        );
        //使用LED模板处理发送到led的短信
        if ($msg['device'] == 1 && (!empty($_W['config']['SMS_LED_Temp']))) {
            $msg['content'] = str_replace('[内容]', $msg['content'], $_W['config']['SMS_LED_Temp']);
        }
        $msg['status'] = addSMSOutBox($db, $msg);
        pdo_insert('out_box', $msg);
    }
}

function getFinanceById($id)
{
    $sql = "SELECT * FROM " . tablename('sms_finance') . " WHERE id = :id ";
    return pdo_fetch($sql, array(':id' => $id));

}

function getFinance($agency, $fileyear, $fileid)
{
    $sql = "SELECT * FROM " . tablename('sms_finance') . " WHERE agency = :agency AND fileyear = :fileyear AND fileid = :fileid";
    return pdo_fetch($sql, array(':agency' => $agency, ':fileyear' => $fileyear, ':fileid' => $fileid));
}

function saveFinance($data, &$row)
{
    //处理：data为界面输入数据，row为主数据
    global $_W;
    $id = 0;
    //检查数据
    if (empty($row)) {
        $row = getFinance($data['agency'], $data['fileyear'], $data['fileid']);

    }

    $id=intval($row['id']);

    if (empty($row)) {

        $insert = array(
            'agency' => $data['agency'],
            'fileyear' => $data['fileyear'],
            'fileid' => $data['fileid'],
            'totalmoney' => $data['totalmoney'],
            'remain' => $data['totalmoney'],
            'firstpage' => $data['firstpage'],
            'creator' => $_W['username'],
            'createid' => $_W['uid'],
            'createtime' => TIMESTAMP,
            'changetime' => TIMESTAMP,

        );
        pdo_insert('sms_finance', $insert);
        $id = pdo_insertid();
        $row = getFinanceById($id);
    } elseif ($row['num'] == 0) {
        $id = $row['id'];
        $update = array(
            'totalmoney' => $data['totalmoney'],
            'remain' => $data['totalmoney'],
            'firstpage' => $data['firstpage'],
            'changetime' => TIMESTAMP,
        );
        pdo_update('sms_finance', $update, array('id' => $id));

    }

    if ($data['sid'] > 0) {
        //检查记录状态
        $update = array(
            'parentid' => $id,
            'lastmoney' => $row['remain'],
            'money' => $data['money'],
            'remain' => $row['remain'] - $data['money'],
            'signpage' => $data['signpage'],
            'grandedate' => TIMESTAMP,
            'changetime' => TIMESTAMP,

        );
        pdo_update('finance_detail', $update, array('id' => $data['sid']));
    } else {
        //检查是否有没通过审核的数据。
        $item = getFinanceLastDetail($id);
        if (empty($item)) {
            $insert = array(
                'parentid' => $id,
                'lastmoney' => $row['remain'],
                'money' => $data['money'],
                'remain' => $row['remain'] - $data['money'],
                'signpage' => $data['signpage'],
                'grandedate' => TIMESTAMP,
                'createid' => $_W['uid'],
                'creator' => $_W['username'],
                'changetime' => TIMESTAMP,
                'createtime' => TIMESTAMP,
            );
            pdo_insert('finance_detail', $insert);
            $detailid = pdo_insertid();
            pdo_update('sms_finance', array('detailid'=>$detailid,'status'=>0), array('id' => $id));
        }

    }
    return $id;
}

function getFinanceLastDetail($data)
{
    if (is_array($data)) {
        $id = $data['detailid'];
        if (!empty($id)) {
            return pdo_fetch($sql = "SELECT * FROM " . tablename('finance_detail') . " WHERE id={$id}");
        } else {
            $pid = $data['id'];
        }
    } else {
        $pid = $data;
    }
    if (!empty($pid)) {
        $nopass = NOPASS;
        $sql = "SELECT * FROM " . tablename('finance_detail') . " WHERE parentid = :parentid AND (status=0 or status={$nopass} )";
        return pdo_fetch($sql, array(':parentid' => $pid));
    }
    return false;
}

function getFinanceDetails($id, $status = -1)
{
    $params = array(':parentid' => $id);
    $sql = "SELECT * FROM " . tablename('finance_detail') . " WHERE parentid = :parentid ";
    if ($status > -1) {
        $sql .= ' AND status = :status ';
        $params[':status'] = $status;
    }
    return pdo_fetchall($sql, $params);
}